<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入内容" v-model="userGet.query">
                        <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="centerDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 添加用户弹框 -->
            <el-dialog
            title="添加用户"
            :visible.sync="centerDialogVisible"
            width="30%"
            center>
                <el-form ref="addform" :model="addform" :rules="rules" label-width="80px">
                    <el-form-item label="用户名称" prop="username">
                        <el-input v-model="addform.username"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password">
                        <el-input type="password" show-password
                         v-model="addform.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addform.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="addform.mobile"></el-input>
                    </el-form-item>
                </el-form>
                
                <span slot="footer" class="dialog-footer">
                    <div class="cancel" @click="cancel('addform')">取 消</div>
                    <div class="determine"  @click="addUserFunc('addform')">确 定</div>
                </span>
            </el-dialog>
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template v-slot="scope">
                        <el-switch
                        v-model="scope.row.mg_state"
                        @change="userStateChange(scope.row)"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180px">
                    <template v-slot="scope">
                        <!--修改-->
                        <el-button type="primary" 
                        @click="showEditdialog(scope.row)"
                        icon="el-icon-edit" size="mini"
                        ></el-button>
                        <!--删除-->
                        <el-button icon="el-icon-delete" type="danger" size="mini"
                        @click="deleteRow(scope.row)"></el-button>
                        <!--权限修改-->
                        <el-tooltip content="角色修改" placement="top" :enterable="false">
                            <el-button type="warning" @click="roleChange(scope.row)"
                            icon="el-icon-s-tools" size="mini"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="userGet.pagenum"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="userGet.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </el-card>

        <!-- 分配角色 -->
        <el-dialog
        title="分配角色"
        :visible.sync="assignRoles"
        @close="closeRolesDialog"
        width="30%"
        center>
            <el-row class="assignRoles">
                <el-col :span="5">当前用户：</el-col>
                <el-col :span="19">{{userInfo.username}}</el-col>
                <el-col :span="5">当前角色：</el-col>
                <el-col :span="19">{{userInfo.role_name}}</el-col>
                <el-col :span="5">分配新角色：</el-col>
                <el-col :span="19">
                    <el-select v-model="selectRoleId" filterable placeholder="请选择">
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <div class="cancel" @click="assignRoles = false">取 消</div>
                <div class="determine"  @click="editRolesFunc()">确 定</div>
            </span>
        </el-dialog>    
        <!-- 修改用户弹框 -->
        <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="30%"
        center>
            <el-form ref="editform" :model="editform" :rules="rules" label-width="80px">
                <el-form-item label="用户名称">
                    <el-input v-model="editform.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editform.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editform.mobile"></el-input>
                </el-form-item>
            </el-form>
            
            <span slot="footer" class="dialog-footer">
                <div class="cancel" @click="cancel('editform')">取 消</div>
                <div class="determine"  @click="editUserFunc('editform')">确 定</div>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getUserinfo,
    putUsersState,
    addUsers,
    editUsers,
    deleteUsers,
    roleUsers,
    getRoles
} from  "@/request/api";
export default {
    name: 'users',
    data(){
        var checkPhone = (rule, value, callback) => {
            const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
            if (!value) {
                return callback(new Error('电话号码不能为空'))
            }
            setTimeout(() => {
                // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
                // 所以我就在前面加了一个+实现隐式转换

                if (!Number.isInteger(+value)) {
                    callback(new Error('请输入数字值'))
                } else {
                    if (phoneReg.test(value)) {
                    callback()
                    } else {
                    callback(new Error('电话号码格式不正确'))
                    }
                }
            }, 100)
        }
        var checkEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!value) {
                return callback(new Error('邮箱不能为空'))
            }
            setTimeout(() => {
                if (mailReg.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入正确的邮箱格式'))
                }
            }, 100)
        }
        return{
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ],
            },
            userGet:{
                query: '',
                pagenum: 1,
                pagesize: 5
            },
            userList: [],
            total: 0,
            centerDialogVisible: false,//添加用户弹框
            editDialogVisible: false,//修改用户
            assignRoles: false,//角色分配
            userInfo: {},
            rolesList: [],//所有角色信息
            selectRoleId: '',
            addform: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            editform: {
                id: '',
                username: '',
                email: '',
                mobile: ''
            },
        }
    },
    mounted(){
        this.getUserInfo();
    },
    methods:{
        getUserInfo(){
            getUserinfo(this.userGet).then(res => {
                if(res.meta.status == 200){
                    this.userList = res.data.users;
                    this.total = res.data.total;
                }else{
                    this.$message.error(res.meta.msg);
                    return false;
                }
            })
        },
        //页码切换
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.userGet.pagesize = val;
            this.getUserInfo();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.userGet.pagenum = val;
            this.getUserInfo();
        },
        //状态修改
        userStateChange(val){
            let data = {
                id: val.id,
                state: val.mg_state
            }
            putUsersState(data).then(res => {
                if(res.meta.status == 200){
                    this.getUserInfo();
                    this.$message.success(res.meta.msg);
                }else{
                    this.$message.error(res.meta.msg);
                    return false;
                }
            })
        },
        //搜索
        searchUser(){
            let userGet = {
                query: this.userGet.query,
                pagenum: 1,
                pagesize: this.userGet.pagesize
            };
            this.userGet = userGet;
            this.getUserInfo();
        },
        //新增用户 addUsers
        addUserFunc(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {//验证成功
                    var loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    addUsers(this.addform).then(res => {
                        if(res.meta.status == 201){
                            this.getUserInfo();
                            this.$message.success(res.meta.msg);
                            this.centerDialogVisible = false
                        }else{
                            this.$message.error(res.meta.msg);
                        }
                        loading.close();
                    })
                } else {
                    return false;
                }
            });
        },
        cancel(formName){
            this.centerDialogVisible = false;
            this.editDialogVisible = false;
            this.$refs[formName].resetFields();
        },
        //修改用户
        showEditdialog(data){
            this.editDialogVisible = true;
            this.editform = {
                id: data.id,
                username: data.username,
                email: data.email,
                mobile: data.mobile
            }
        },
        editUserFunc(formName){
            this.$refs[formName].validate(async valid => {
                if(!valid) return;
                var loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                editUsers(this.editform).then(res => {
                    if(res.meta.status == 200){
                        this.getUserInfo();
                        this.$message.success(res.meta.msg);
                        this.editDialogVisible = false
                    }else{
                        this.$message.error(res.meta.msg);
                    }
                    loading.close();
                })
            });
        },
        //删除用户
        deleteRow(info){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteUsers(info).then(res => {
                    if(res.meta.status == 200){
                        this.getUserInfo();
                        this.$message.success(res.meta.msg);
                    }else{
                        this.$message.error(res.meta.msg);
                    }
                })
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
        },
        //分配用户角色
        roleChange(info){
            this.assignRoles = true;
            this.userInfo = info;
            getRoles().then(res=>{
                if(res.meta.status == 200){
                    this.rolesList = res.data
                }else{
                    this.$message.error(res.meta.msg);
                }
            })
        },
        editRolesFunc(){
            if(!this.selectRoleId){
                return this.$message.error('选择分配的角色');
            }
            roleUsers(this.userInfo.id,{rid:this.selectRoleId}).then(res=>{
                if(res.meta.status == 200){
                    this.getUserInfo();
                    this.assignRoles = false;
                    this.$message.success(res.meta.msg);
                }else{
                    this.$message.error(res.meta.msg);
                }
            })
        },
        closeRolesDialog(){
            this.selectRoleId = '';
            this.userInfo = {}
        }
    }
}
</script>

<style lang="less" scoped>
.assignRoles{
    .el-col{
        height: 50px;
        line-height: 50px;
    }
}
</style>